﻿//-----------------------------------------------------------------------
// <copyright file="Cleanup.cs" company="Erik Lieben">
//     Copyright Erik Lieben. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace ErikLieben.CssPreprocessor
{
    using System.Diagnostics.Contracts;
    using System.Text.RegularExpressions;

    /// <summary>
    /// Generic class containing cleanup methods
    /// </summary>
    public static class Cleanup
    {
        /// <summary>
        /// Cleans up CSS and removed unneeded characters.
        /// </summary>
        /// <param name="source">The source css to process.</param>
        /// <returns>The clean css code, without useless characters</returns>
        public static string CleanUpCss(string source)
        {
            // Nothing to process? then return.
            if (string.IsNullOrWhiteSpace(source))
            {
                return source;
            }

            // Remove double space, tab, return and comments
            source = Regex.Replace(source, "\\s\\s|\\n|\\r|\\t|/\\*[\\d\\D]*?\\*/", string.Empty);

            // Remove useless characters
            source = source.Replace(" {", "{");
            source = source.Replace("{ ", "{");
            source = source.Replace(" :", ":");
            source = source.Replace(": ", ":");
            source = source.Replace(", ", ",");
            source = source.Replace("; ", ";");
            source = source.Replace(";}", "}");

            // REVIEW: Not faster according to tests, takes around 1500ms more on 1000 iterations
            ////source = Regex.Replace(source, "\\s(?<m>(\\{|:|,|;))", m => m.Groups["m"].Value);
            ////source = Regex.Replace(source, "(?<m>(\\{|:|,|;))\\s", m => m.Groups["m"].Value);
            return source;
        }

        /// <summary>
        /// Removes the variable tags (@variable name {parameters}).
        /// </summary>
        /// <param name="source">The source css to process.</param>
        /// <returns>The css code cleaned from variable tags</returns>
        public static string RemoveVariableTags(string source)
        {
            //// Method contract
            ////Contract.Requires(source != null);

            // Nothing to process? then return.
            if (string.IsNullOrWhiteSpace(source))
            {
                return source;
            }

            return Regex.Replace(source, "@variable.*?\\{.*?\\}", string.Empty);
        }
    }
}
